<template>
  <!-- /api/userlogin  管理员登录 -->
  <div class="login">
    <el-row>
      <!-- span：占据的份数 -->
      <!-- offset：偏移量 -->
      <el-col :span="8" :offset="8">
        <div class="login-div">
          <p>小U商城后台管理系统</p>
          <!-- model:表单中的数据 -->
          <!-- rules:表单中的校验规则 -->
          <!-- prop：校验对应的字段 -->
          <el-form ref="form" :model="form" :rules="rules">
            <el-form-item prop="username">
              <el-input v-model="form.username">
                <!-- 具名插槽 -->
                <i class="el-icon-user" slot="prepend"></i>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="form.password" show-password>
                <!-- 具名插槽 -->
                <i class="el-icon-lock" slot="prepend"></i>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button class="login-btn" type="primary" @click="onSubmit"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {login} from '../api'
export default {
  data() {
    return {
      // 表单中的数据
      form: {
        username: "123456",
        password: "123456",
      },
      // 校验规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    onSubmit() {
      // this.$refs.form选择子组件，validate是子组件中的函数
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 值为真，表示校验通过
          let res = await login(this.form);
          if(res.code === 200) {
            // 保存用户信息
            this.$store.commit('saveUserInfo', res.list)
            this.$router.push('/');
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style>
.login {
  width: 100vw;
  height: 100vh;
  background-image: url("../assets/loginbg.jpeg");
}
.login .login-div {
  margin-top: 100px;
  height: 200px;
  padding: 20px;
  background-color: #fff;
  border-radius: 6px;
}
/* 覆盖element的样式 */
.login .login-btn {
  width: 100%;
}
</style>